package com.xuhao.examai.exam.application.services;

import com.xuhao.examai.exam.domain.models.Exam;
import com.xuhao.examai.exam.infrastructure.persistence.ExamRecord;
import com.xuhao.examai.model.entity.Question;
import com.xuhao.examai.model.entity.AnswerRecord;
import com.xuhao.examai.model.vo.ResultVO;
import com.xuhao.examai.exam.infrastructure.persistence.ExamRepository;
import com.xuhao.examai.repository.ExamRecordRepository;
import com.xuhao.examai.repository.QuestionRepository;
import com.xuhao.examai.repository.AnswerRecordRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class ExamServiceImpl implements ExamService {
	private final ExamRepository examRepository;
	private final ExamRecordRepository examRecordRepository;
	private final QuestionRepository questionRepository;
	private final AnswerRecordRepository answerRecordRepository;

	public ExamServiceImpl(ExamRepository examRepository,
			ExamRecordRepository examRecordRepository,
			QuestionRepository questionRepository,
			AnswerRecordRepository answerRecordRepository) {
		this.examRepository = examRepository;
		this.examRecordRepository = examRecordRepository;
		this.questionRepository = questionRepository;
		this.answerRecordRepository = answerRecordRepository;
	}

	@Override
	public Exam getExamById(Long id) {
		return examRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("考试不存在"));
	}

	@Override
	public Exam getExamById(String examId) {
		Long id = Long.parseLong(examId);
		return examRepository.findById(id)
				.orElseThrow(() -> new RuntimeException("考试不存在"));
	}

	@Override
	@Transactional
	public Long startExam(Long examId) {
		// 创建考试记录
		ExamRecord record = new ExamRecord();
		record.setId(Math.abs(UUID.randomUUID().getMostSignificantBits()));
		record.setExam(examRepository.findById(examId)
				.orElseThrow(() -> new RuntimeException("考试不存在")));
		record.setStartTime(LocalDateTime.now());
		record.setStatus("in_progress");

		examRecordRepository.save(record);
		return record.getId();
	}

	@Override
	public List<Question> getExamQuestions(String examId) {
		return questionRepository.findByExamId(Long.parseLong(examId));
	}

	@Override
	@Transactional
	public void submitAnswer(Long examRecordId, Long questionId, String answer) {
		AnswerRecord answerRecord = new AnswerRecord();
		answerRecord.setId(Math.abs(UUID.randomUUID().getMostSignificantBits()));
		answerRecord.setExamRecord(examRecordRepository.findById(examRecordId)
				.orElseThrow(() -> new RuntimeException("考试记录不存在")));
		answerRecord.setQuestion(questionRepository.findById(questionId)
				.orElseThrow(() -> new RuntimeException("问题不存在")));
		answerRecord.setAnswer(answer);
		answerRecord.setCreatedAt(LocalDateTime.now());

		answerRecordRepository.save(answerRecord);
	}

	@Override
	@Transactional
	public void submitExam(String examRecordId) {
		ExamRecord record = examRecordRepository.findById(Long.parseLong(examRecordId))
				.orElseThrow(() -> new RuntimeException("考试记录不存在"));

		record.setStatus("submitted");
		record.setEndTime(LocalDateTime.now());
		examRecordRepository.save(record);

		// 这里可以添加自动评分逻辑
	}

	@Override
	@Transactional
	public void saveDraft(String examRecordId) {
		ExamRecord record = examRecordRepository.findById(Long.parseLong(examRecordId))
				.orElseThrow(() -> new RuntimeException("考试记录不存在"));

		record.setStatus("draft");
		examRecordRepository.save(record);
	}

	@Override
	@Transactional
	public ResultVO<Exam> createExam(Exam exam) {
		exam.setIsPublished(false);
		Exam savedExam = examRepository.save(exam);
		return ResultVO.success(savedExam);
	}

	@Override
	@Transactional
	public ResultVO<Exam> updateExam(Exam exam) {
		if (!examRepository.existsById(exam.getId())) {
			return ResultVO.error(404, "考试不存在");
		}
		Exam updatedExam = examRepository.save(exam);
		return ResultVO.success(updatedExam);
	}

	@Override
	@Transactional
	public ResultVO<Void> deleteExam(Long id) {
		if (!examRepository.existsById(id)) {
			return ResultVO.error(404, "考试不存在");
		}
		examRepository.deleteById(id);
		return ResultVO.success(null);
	}

	@Override
	public List<Exam> getAllExams() {
		return examRepository.findAll();
	}

	@Override
	public List<Exam> getPublishedExams() {
		return examRepository.findByIsPublishedTrue();
	}

	@Override
	@Transactional
	public ResultVO<Void> publishExam(Long id) {
		Optional<Exam> examOptional = examRepository.findById(id);
		if (!examOptional.isPresent()) {
			return ResultVO.error(404, "考试不存在");
		}
		Exam exam = examOptional.get();
		exam.setIsPublished(true);
		examRepository.save(exam);
		return ResultVO.success(null);
	}

	@Override
	@Transactional
	public ResultVO<Void> cancelExam(Long id) {
		Optional<Exam> examOptional = examRepository.findById(id);
		if (!examOptional.isPresent()) {
			return ResultVO.error(404, "考试不存在");
		}
		Exam exam = examOptional.get();
		exam.setIsPublished(false);
		examRepository.save(exam);
		return ResultVO.success(null);
	}
}
